import 'dart:convert';

import 'package:dart_sm/dart_sm.dart';
import 'package:dio/dio.dart';
import 'package:xuance/bean/PublicKeyBean.dart';
import 'package:xuance/util/cache_util.dart';

class SignInterceptor extends Interceptor {
  final methods = ["POST", "PUT"];

  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    PublicKeyBean? publicKey = await CacheUtil.getPubKey();
    if (methods.contains(options.method.toUpperCase()) &&
        options.data.runtimeType != FormData &&
        publicKey != null) {
      var jsonStr = "";
      if (options.data is num ||
          options.data is String ||
          options.data is bool) {
        jsonStr = "${options.data}";
      } else {
        jsonStr = json.encode(options.data);
      }
      int? serverTime = DateTime.now().millisecondsSinceEpoch;
      String dataHash = SM3.hash(jsonStr);
      String dataSign = SM2.encrypt(dataHash, publicKey.publicKey!);
      String timeSign =
          SM2.encrypt(serverTime.toString(), publicKey.publicKey!);
      options.headers["X-Sign"] = "04$dataSign";
      options.headers["X-Timestamp"] = "04$timeSign";
    }
    super.onRequest(options, handler);
  }
}
